### Bootstrap the joiners model specification

date()
library("tidyverse")
library("foreach")
library("maxLik")
source("backend_joiners.r")
sessionInfo()


load("confirm_boot_joiners.rda")
load("confirm_fit_base.rda")
load("results/fit_joiners.rda")
load("results/boot_index_joiners.rda")


## Set to FALSE to estimate from scratch (takes much longer)
CONFIRM_MODE <- TRUE

## Run bootstrap using indices generated in previous script
boot_joiners <- vector("list", length(fit_joiners))
for (i in seq_along(boot_joiners)) {
  fit <- fit_joiners[[i]]
  boot_joiners[[i]] <- foreach (b = 1:25, .combine = "rbind") %do% {
    cat("Imputation ", i, ", bootstrap iteration ", b, ", ", date(), "\n", sep = "")
    id_disp_boot <- boot_index_joiners[[i]][b, ]
    id_map <- tibble(id = seq_along(id_disp_boot), id_old = id_disp_boot)
    boot_dispute <-  left_join(id_map,
                               fit$data_dispute,
                               by = c("id_old" = "id"))
    boot_participant <- left_join(id_map,
                                  fit$data_participant,
                                  by = c("id_old" = "id"))
    if (CONFIRM_MODE) {
      init <- confirm_boot_joiners[[i]][b, ]
    } else {
      init <- map(confirm_fit_base, ~ .x[str_detect(names(.x), "^(beta|gamma)")])[[i]]
    }
    boot_cf <- est_structwar_ac(f_dispute = fit$f_dispute,
                                f_participant = fit$f_participant,
                                data_dispute = boot_dispute,
                                data_participant = boot_participant,
                                n_halton = fit$n_halton,
                                coef_only = TRUE,
                                init = init,
                                scale = FALSE,
                                reltol = 1e-14,
                                iterlim = 5000,
                                finalHessian = FALSE,
                                printLevel = 1)
    boot_cf
  }
}


save(boot_joiners, file = "results/boot_joiners.rda")


date()
